<style lang="scss" scoped>
@import "@/assets/css/variable";
.applyActivity {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  background-color: $main-bgc;
  min-height: 100%;
  font-size: 1.2rem;
  overflow: auto;
  box-sizing: border-box;
  .title-box {
    padding: 1.8rem 1.6rem;
    display: flex;
    .left-line {
      flex: 0 0 0.3rem;
    }
    .title {
      padding-left: 0.5rem;
      font-size: 1.5rem;
      padding-bottom: 0 !important;
    }
  }
  .fix-bottom {
    position: fixed;
    bottom: 1rem;
    left: 0;
    right: 0;
    width: 100%;
    z-index: 3;
    box-sizing: border-box;
  }
  .van-field {
    position: relative;
    .m-colorPicker {
      width: 50px;
      position: absolute;
      top: 5px;
      left: 0;
    }
  }
}
.van-button__text {
  font-size: 1.4rem !important;
}
.van-field__error-message {
  text-align: right !important;
}
</style>
<template>
  <div class="applyActivity">
    <div class="title-box">
      <span
        class="left-line"
        :style="{ backgroundColor: $store.getters.getMainColor }"
      ></span>
      <span class="title">报名模板</span>
    </div>
    <div class="base-info padding-lr">
      <van-form>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          required
          v-model="form.title"
          label="活动名称"
          placeholder="请填写活动名称"
          input-align="right"
        />
        <div class="field-box">
          <div class="label">
            活动封面
            <span class="tip fs-12 color-s">建议上传比例为4:3的图片</span>
          </div>
          <!-- <van-uploader v-model="form.cover" max-count="1" :before-read="beforeRead" :after-read="afterRead" :max-size="1000 * 1024" @oversize="onOversize"/> -->
          <div class="my-img">
            <!-- <img :src="form.cover" alt=""> -->
            <van-image :src="form.cover" fit="scale-down" />
            <span class="change-pic" @click="changePic">{{form.cover?'更换图片':'上传图片'}}</span>
            <input
              type="file"
              class="file-input d-none"
              ref="fileInput"
              @change="handleFileChange"
            />
          </div>
        </div>

        <van-cell
          title="活动开始时间"
          is-link
          :value="form.start_time"
          @click="showStartTimePopup = true"
          required
          label-width="90"
        />
        <van-cell
          title="活动截止时间"
          is-link
          :value="form.end_time"
          @click="showEndTimePopup = true"
          required
          label-width="90"
        />
      </van-form>
    </div>
    <div class="base-info padding-lr margT-l">
      <van-form>
        <!-- 通过 pattern 进行正则校验 -->

        <van-field
          name="switch"
          label="颜色主题"
          label-width="7rem"
          required
          class="van_field"
          readonly
        >
          <template #right-icon>
            <colorPicker
              v-model="form.theme_color"
              @change="headleChangeColor"
            ></colorPicker>
          </template>
        </van-field>
		<!-- <div class="color-s margT-s tip4help">
		  背景音乐是在PC端的[系统设置-多媒体-音乐库]中所预先添加的
		</div> -->
        <van-field
            label="背景音乐"
            @click.prevent="changeMusic"
            v-model="form.musicName"
            input-align="right"
            readonly
            clearable
            label-width="10rem"
            placeholder="请选择背景音乐"
			right-icon="warning-o"
			@click-right-icon="clickRightIcon(e)"
          />

        <van-action-sheet
        v-model="showMusic"
        :actions="musicList"
        @select="onMusic"
      />
		
		<van-field
		  required
		  v-model="form.sharetitle"
		  label="分享标题"
		  placeholder="微信中分享后所显示的标题"
		  input-align="right"
		/>
        <div class="field-box">
          <div class="label">
            分享缩略图
            <span class="tip fs-12 color-s">建议上传比例为4:3的图片</span>
          </div>
          <!-- <van-uploader v-model="form.cover" max-count="1" :before-read="beforeRead" :after-read="afterRead" :max-size="1000 * 1024" @oversize="onOversize"/> -->
          <div class="my-img">
            <!-- <img :src="form.cover" alt=""> -->
            <van-image :src="form.shareimg" fit="scale-down" />
            <span class="change-pic" @click="changePic4shareimg">更换图片</span>
            <input
              type="file"
              class="file-input d-none"
              ref="fileInput4shareimg"
              @change="handleFileChange4shareimg"
            />
          </div>
        </div>
        <van-field
          required
          v-model="form.share_describe"
          label="分享描述"
          type="textarea"
          autosize
          rows="5"
          placeholder="微信中分享活动后所显示的描述"
          input-align="right"
        />
      </van-form>
    </div>
    <div class="introduce padding-all-l margT-l">
      <h2 class="introduce-title t-bold">活动介绍</h2>
      <div v-for="(item, index) in form.introduce" :key="Number(item.id)">
        <my-text
          v-if="item.type === 'text'"
          class="margT-l"
          :editorHtml="item.value"
          :id="Number(item.id)"
          :index="index"
          @editorHtmlChange="editorHtmlChange"
          @deleteIntroduceItem="deleteIntroduceItem"
          @downIntroduceItem="downIntroduceItem"
          @upIntroduceItem="upIntroduceItem"
        >
        </my-text>
        <!-- <my-img
          v-if="item.type === 'img' && item.value"
          class="margT-l"
          :value="item.value"
          :id="Number(item.id)"
          :index="index"
          @ChangeFile="ChangeFile"
          @deleteIntroduceItem="deleteIntroduceItem"
          @downIntroduceItem="downIntroduceItem"
          @upIntroduceItem="upIntroduceItem"
        >
        </my-img> -->
      </div>
      <div class="btnAddSomeBox margT-l">
        <div class="addSome">
          <van-button size="small" type="default" block @click="addTextBtn"
            >添加富文本</van-button
          >
        </div>
        <!-- <div class="interval"></div>
        <div class="addSome">
          <van-button size="small" type="default" block @click="addPicBtn"
            >添加图片{{ imgNum }}/10</van-button
          >
          <input
            type="file"
            class="file-input d-none"
            ref="addPicInput"
            @change="addPicInputChange"
          />
        </div> -->
      </div>
    </div>
    <div class="base-info padding-lr">
      <van-field name="switch" label="是否开启支付功能" label-width="12rem">
        <template #right-icon>
          <van-switch
            v-model="switchChecked"
            size="20"
            @change="changeSwitch"
          />
        </template>
      </van-field>
      <van-field
        v-show="switchChecked"
        v-model="form.apply_charge"
        right-icon="gold-coin-o"
        input-align="right"
        name="type"
        clearable
        required
        label="报名费用"
        label-width="12rem"
        placeholder="0.01~9999.00元"
      />
    </div>
    <div class="introduce padding-all-l margT-l">
      <h2 class="introduce-title">报名表单</h2>
      <div class="color-s margT-s">报名表单可在后台管理系统中自定义</div>
      <div class="margT-l" v-if="form.create_form">
        <!-- <k-form-build ref="kfb" :value="form.create_form" /> -->
        <van-field
          required
          v-for="(item, index) in form.create_form.list"
          :key="index"
          :label="item.label"
          disabled
          :placeholder="item.options.placeholder"
          input-align="right"
        />
      </div>
      <!-- <button @click="handleGetData">获取数据</button> -->
    </div>

    <protocol-title @protocolClick="protocolClick" @radioClick="radioClick"></protocol-title>

    <protocol-text
      v-if="protocolShow"
      :protocolShow="protocolShow"
      @iconClick="iconClick"
      :btn_color="$store.getters.getMasterColor"
      :theme_color="form.theme_color"
    ></protocol-text>

    <div class="tabbar-height"></div>
    <van-popup v-model:show="showStartTimePopup" position="bottom">
      <van-datetime-picker
        v-model="start_time"
        id="start_time"
        type="datetime"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="startTimeConfirm"
        active-class="active-style"
      />
    </van-popup>
    <van-popup v-model:show="showEndTimePopup" position="bottom">
      <van-datetime-picker
        v-model="end_time"
        id="end_time"
        type="datetime"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="endTimeConfirm"
        active-class="active-style"
      />
    </van-popup>
    <div class="fix-bottom padding-lr">
      <van-button
        :color="$store.getters.getMasterColor"
        block
        @click="submit"
        >{{ is_edit == 0 ? "发布活动" : "保存修改" }}</van-button
      >
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import { Dialog, Toast } from "vant";
import { Image as VanImage } from "vant";
import MyText from "@/components/MyText";
import MyImg from "@/components/MyImg";
import ProtocolTitle from "@/components/ProtocolTitle";
import ProtocolText from "@/components/ProtocolText";
// import utils from '@/assets/js/utils.js'
import { myMixins } from "@/assets/js/mixins.js";
// import { quillEditor } from 'vue-quill-editor'
// import 'quill/dist/quill.core.css'
// import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'
// const formatDate = (date) => `${date.getFullYear()}-${(date.getMonth() + 1)<10?'0'+(date.getMonth() + 1):date.getMonth() + 1}-${(date.getDate())<10?'0'+(date.getDate()):date.getDate()} ${(date.getHours())<10?'0'+(date.getHours()):date.getHours()}:${(date.getMinutes())<10?'0'+(date.getMinutes()):date.getMinutes()}`;
export default {
  name: "ApplyActivity",
  mixins: [myMixins],
  components: {
    [Dialog.name]: Dialog,
    [Toast.name]: Toast,
    VanImage,
    MyText,
    MyImg,
    ProtocolTitle,
    ProtocolText,
    // quillEditor
  },
  data() {
    return {
      showStartTimePopup: false,
      showEndTimePopup: false,
      name: "满天星",
      pattern: /\d{6}/,
      start_time: new Date(),
      end_time: new Date(),
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2028, 10, 1),
      case_id: "",
      form: {
        title: "",
        apply_charge: "0.01",
        cover:"http://youmihuodongbao.oss-cn-hangzhou.aliyuncs.com/UMI_20210805175222_581670674cd8421340c375ec5be8af5d.jpeg",
        start_time: this.$utils
          .formatDateYMDHM(new Date(new Date().getTime()))
          .toString(),
        end_time: this.$utils
          .formatDateYMDHM(new Date(new Date().getTime() + 86400000 * 7))
          .toString(),
        introduce: [],
        create_form: "" || this.$store.state.create_form,
        shareimg: "http://youmihuodongbao.oss-cn-hangzhou.aliyuncs.com/UMI_20210805175222_581670674cd8421340c375ec5be8af5d.jpeg",
        share_describe: "",
        sharetitle: "",
        theme_color: "#ff7200",
        music: "",
        musicName: "",
        model: "" || this.$route.query.model,
        merchant_id: null
      },
      switchChecked: false,
      textNum: 0,
      imgNum: 0,
      is_edit: 0,
      jsonData: {},
      openid: "",
      protocolShow: false,
      radioChecked: false,
      showMusic: false,
      musicList: [],
    };
  },
  created() {
    this.getMusicPage()
  },
  mounted() {
    // this.getTypeNum(this.form.introduce)
    if (process.env.NODE_ENV == "production") {
      //线上环境
      this.openid = localStorage.getItem("OPENID") || "没获取到";
      this.getItemopenid(this.openid)
    } else {
      this.openid = this.$store.state.openid;
    }
    this.getActivityItem();
    this.is_edit = this.$route.query.is_edit;
    this.case_id = this.$route.query.case_id;
  },
  methods: {
	clickRightIcon(e){
		// e.preventDefault()
		//如果提供了事件对象，则这是一个非IE浏览器 
		if ( e && e.stopPropagation ) {
			//因此它支持W3C的stopPropagation()方法
			e.stopPropagation(); 
		}
		else{
			//否则，我们需要使用IE的方式来取消事件冒泡 
			window.event.cancelBubble = true; 
		}
		Dialog.alert({
		  title: "系统提示",
		  message: "背景音乐列表是在PC端的[系统设置-多媒体-音乐库]中所预先添加的",
		  showCancelButton:true
		}).then(() => {
		  // on close
		});
	},
    changeMusic(e) {
      console.log(e);
		  e.preventDefault()
      this.showMusic = true
    },
    // 获取音乐数据
    getMusicPage() {
      this.$request.getMusicPage().then(res => {
        this.musicList = res.data.data
      })
    },
    onMusic(value) {
      console.log(value.url);
      this.showMusic = false
      this.form.musicName = value.name
      this.form.music = value.url
    },
    // 选择框
    radioClick(value) {
      this.radioChecked = value
    },
    protocolClick() {
      this.protocolShow = true;
    },
    iconClick() {
      this.protocolShow = false;
    },
    // 更改颜色
    headleChangeColor(value) {
      this.form.theme_color = value;
    },
    changeSwitch(value) {
      console.log("value", value);
      this.switchChecked = value;
    },
    handleGetData() {
      // 使用getData函数获取数据
      this.$refs.kfb
        .getData()
        .then((values) => {
          console.log("验证通过", values);
        })
        .catch(() => {
          console.log("验证未通过，获取失败");
        });
    },
    changePic() {
      this.$refs.fileInput.click();
    },
    changePic4shareimg() {
      this.$refs.fileInput4shareimg.click();
    },
    addPicBtn() {
      this.$refs.addPicInput.click();
    },
    addPicInputChange(e) {
      const _this = this;
      const img = e.target.files[0];
      if (img.type != "image/jpeg" && img.type != "image/png") {
        Toast("请上传jpg或png格式的图片");
        return false;
      }
      if (img.size > 2000 * 1024) {
        Toast("图片大小请不要超过2M");
        return;
      }
      this.$utils.blobToDataURL(img, (base64Url) => {
        let formData = new FormData();
        formData.append("file", img);
        console.log("formData", formData);
        this.$request.uploadPic(formData).then((res) => {
          console.log("res", res);
          let introduce = this.form.introduce;
          introduce.push({
            id:
              Number(
                introduce[introduce.length - 1] &&
                  introduce[introduce.length - 1].id
              ) + 1 || 1,
            type: "img",
            value: res.data.url,
          });
          this.form.introduce = introduce;
          this.getTypeNum(this.form.introduce);
        });
      });
      // utils.blobToDataURL(img, (base64Url) => {
      //   let introduce = this.form.introduce
      //   introduce.push({
      //     id: (Number(introduce[introduce.length-1] && introduce[introduce.length-1].id)+1) || 1,
      //     type:"img",
      //     value: base64Url
      //   })
      //   this.form.introduce = introduce
      //   this.getTypeNum(this.form.introduce)
      // });
    },
    handleFileChange4shareimg(e) {
      const _this = this;
      const img = e.target.files[0];
      if (
        img.type != "image/jpeg" &&
        img.type != "image/png" &&
        img.type != "image/gif"
      ) {
        Toast("请上传jpg或png格式的图片");
        return false;
      }
      if (img.size > 2000 * 1024) {
        Toast("图片大小请不要超过2M");
        return;
      }
      this.$utils.blobToDataURL(img, (base64Url) => {
        let formData = new FormData();
        formData.append("file", img);
        _this.$request.uploadPic(formData).then((res) => {
          _this.form.shareimg = res.data.url;
        });
      });
    },
    handleFileChange(e) {
      const _this = this;
      console.log("e", e);
      const img = e.target.files[0];
      if (
        img.type != "image/jpeg" &&
        img.type != "image/png" &&
        img.type != "image/gif"
      ) {
        Toast("请上传jpg或png格式的图片");
        return false;
      }
      if (img.size > 2000 * 1024) {
        Toast("图片大小请不要超过2M");
        return;
      }
      this.$utils.blobToDataURL(img, (base64Url) => {
        let formData = new FormData();
        formData.append("file", img);
        console.log("formData", formData);
        _this.$request.uploadPic(formData).then((res) => {
          console.log("res", res);
          _this.form.cover = res.data.url;
          console.log("_this.form.cover", _this.form.cover);
        });
      });
      // utils.blobToDataURL(img, (base64Url) => {
      //   _this.form.cover = base64Url
      //   console.log("_this.form.cover",_this.form.cover)
      // });
    },
    submit() {
      const form = this.form;
      if (this.switchChecked) {
        if (form.apply_charge < 0.01) {
          Toast(`报名费用至少需大于等于0.01元`);
          return;
        }
      }

      if (this.radioChecked != true) {
        Dialog.alert({
          title: "温馨提示",
          message: "请同意用户协议",
        }).then(() => {
          // on close
          return;
        });
        return;
      }

      let params = {
        openid: this.openid,
        title: form.title,
        cover: form.cover || this.loadimg,
        is_need_pay: this.switchChecked ? 1 : 2,
        apply_charge: this.switchChecked ? form.apply_charge : "0.01",
        start_time: form.start_time,
        end_time: form.end_time,
        introduce: JSON.stringify(form.introduce),
        create_form: JSON.stringify(form.create_form),
        sharetitle: form.sharetitle,
        shareimg: form.shareimg || this.loadimg,
        share_describe: form.share_describe,
        model: form.model,
        theme_color: form.theme_color,
        music: form.music,
        case_id: this.case_id,
        merchant_id:  this.form.merchant_id,
        // activity_type:1 // 没用了的字段
      };
	  //加首页案例被使用次数的时候要传case_id
      if (this.case_id) params.case_id = this.case_id;
      // if(this.$utils.hasNull(params)){
      //   Toast(`请填写完整信息`);
      //   return;
      // }
      if (this.is_edit == 1) params.id = form.id;
      // params.cover = this.cover
      this.$request.activitySave(params).then((res) => {
        if (res.ret == 200) {
          this.$router.replace("/manage");
          Toast("操作成功");
        } else {
          Dialog.alert({
            title: "系统提示",
            message: res.msg.slice(5),
          }).then(() => {
            // on close
          });
        }
      });
    },
    getActivityItem() {
      if(this.$route.query.model) return
      let params = {
        id: Number(this.$route.params.id),
      };
      this.$request.getActivityItem(params).then((res) => {
        let data = res.data;
        this.form.music = data.music
        this.musicList.forEach(item => {
          if(item.url == data.music) {
            return this.form.musicName = item.name
          }
        })
        this.form.id = data.id;
        this.form.title = data.title;
        this.form.cover = data.cover || this.loadimg;
        this.form.is_need_pay = data.is_need_pay == 1 ? true : false;
        this.switchChecked = data.is_need_pay == 1 ? true : false;
        this.form.apply_charge = data.apply_charge > 0.0 ? data.apply_charge : "0.01";
        this.form.introduce = data.introduce;
        this.form.start_time = this.$utils.parseToDateYMDHM(data.start_time); // 开始时间
        this.start_time = this.$utils.parseToDateYMDHM(data.start_time); // 开始时间
        this.start_time = new Date(this.start_time);
        this.form.end_time = this.$utils.parseToDateYMDHM(data.end_time); // 结束时间
        this.end_time = this.$utils.parseToDateYMDHM(data.end_time); // 结束时间
        this.end_time = new Date(this.end_time);
        this.form.create_form = data.create_form;
        // alert(JSON.stringify(this.form.create_form))
        // localStorage.setItem('kk', JSON.stringify(this.form.create_form))
        this.form.sharetitle = data.sharetitle;
        this.form.shareimg = data.shareimg || this.loadimg;
        this.form.share_describe = data.share_describe;
        this.form.theme_color = data.theme_color;
        this.form.model = data.model || "applyActivity";
        this.form.merchant_id = localStorage.getItem("merchant_id");
        
        this.$forceUpdate();
        this.getTypeNum(this.form.introduce);
      });
    },
    addTextBtn() {
      let introduce = this.form.introduce || [];
      introduce.push({
        id:
          Number(
            introduce[introduce.length - 1] &&
              introduce[introduce.length - 1].id
          ) + 1 || 1,
        type: "text",
        value: "",
      });
      this.form.introduce = introduce;
      this.getTypeNum(this.form.introduce);
    },
    // 统计富文本框和图片的个数
    getTypeNum(arr) {
      this.textNum = 0;
      this.imgNum = 0;
      if(arr.length == 0) return
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].type === "text" && arr[i].value) {
          this.textNum++;
        } else if (arr[i].type === "img" && arr[i].value) {
          this.imgNum++;
        }
      }
    },
    // 上移
    upIntroduceItem(index) {
      let introduce = this.form.introduce;
      console.log("introduce[index - 1]", introduce[index - 1]);
      if (introduce[index - 1]) {
        const type = introduce[index - 1].type;
        const value = introduce[index - 1].value;
        introduce[index - 1].type = introduce[index].type;
        introduce[index - 1].value = introduce[index].value;
        introduce[index].type = type;
        introduce[index].value = value;
        this.form.introduce = introduce;
      } else {
        Toast("已在最后面");
      }
    },
    // 下移
    downIntroduceItem(index) {
      console.log("downIntroduceItem", this.index);
      let introduce = this.form.introduce;
      console.log("introduce[index + 1]", introduce[index + 1]);
      if (introduce[index + 1]) {
        const type = introduce[index + 1].type;
        const value = introduce[index + 1].value;
        introduce[index + 1].type = introduce[index].type;
        introduce[index + 1].value = introduce[index].value;
        introduce[index].type = type;
        introduce[index].value = value;
        this.form.introduce = introduce;
      } else {
        Toast("已在最前面");
      }
    },
    deleteIntroduceItem(id) {
      let introduce = this.form.introduce;
      if (introduce.length <= 1) {
        Toast("活动介绍不能为空");
        return;
      }
      this.form.introduce = introduce.filter((item) => {
        return item.id != id;
      });
      this.getTypeNum(this.form.introduce);
      // introduce.splice(index,1)
      // this.form.introduce = introduce
    },
    onEditorChange(value) {
      console.log(value);
    },
    ChangeFile(item) {
      let introduce = this.form.introduce;
      let newIntroduce = introduce.map((i) => {
        if (i.id == item.id) {
          i.value = item.value;
        }
        return i;
      });
      this.form.introduce = newIntroduce;
    },
    editorHtmlChange(item) {
      let introduce = this.form.introduce;
      let newIntroduce = introduce.map((i) => {
        if (i.id == item.id) {
          i.value = item.value;
        }
        return i;
      });
      this.form.introduce = newIntroduce;
    },
    startTimeConfirm(value) {
      this.showStartTimePopup = false;
      this.form.start_time = this.$utils.parseToDateYMDHM(value);
      this.start_time = this.$utils.parseToDateYMDHM(value);
      console.log("this.start_time", this.start_time);
    },
    endTimeConfirm(value) {
      this.showEndTimePopup = false;
      this.form.end_time = this.$utils.parseToDateYMDHM(value);
      this.end_time = this.$utils.parseToDateYMDHM(value);
    },
    onOversize(file) {
      console.log("file", file);
      console.log("文件大小不能超过 1M");
    },
    afterRead(value) {
      console.log("file.value", value);
      // this.form.cover = value.content
    },
    beforeRead(file) {
      if (file.type != "image/jpeg" && file.type != "image/png") {
        Toast("请上传jpg或png格式的图片");
        return false;
      }
      return true;
    },
  },
};
</script>
